package com.tczs.client;

import com.tczs.client.service.ClientService;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.log4j.Logger;

public class ClientTimeOutHandler extends ChannelDuplexHandler {

    private static Logger logger = Logger.getLogger(ClientTimeOutHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if(e.state() == IdleState.WRITER_IDLE){
                ctx.channel().writeAndFlush("01 I live still ..."+ ClientService.SPILT_STR);
            }
            if (e.state() == IdleState.READER_IDLE) {
                ctx.channel().writeAndFlush("02 读超时断开连接 ..."+ClientService.SPILT_STR);
                logger.info("客户端:"+ctx.channel().id()+" read time out,断开连接");
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Long id = Client.CHANNEL_ID_LONG_MAP.get(ctx.channel().id());
                        Client client = Client.LONG_CLIENT_MAP.get(id);
                        client.close();
                    }
                });
                thread.start();
                ctx.channel().close();
            }
        }
    }
}
